package com.ruubypay.miss.miniotest.demos.web;

import cn.hutool.core.lang.Snowflake;
import com.ruubypay.miss.miniotest.pojo.Order;
import com.ruubypay.miss.miniotest.repository.OrderRepository;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author fj
 * @date 2025/2/25 09:28
 */
@RestController
@RequestMapping(value = "/order")
public class OrderController {

    @Resource
    private OrderRepository orderRepository;
    @Resource
    private Snowflake snowflake;

    @GetMapping(value = "/{id}")
    public ResponseEntity<Order> getOrder(@PathVariable("id") Long id){
        return ResponseEntity.ok(orderRepository.findById(id).orElse(null));
    }

    @PostMapping()
    public ResponseEntity<Void> saveOrder(@RequestBody Order order){
        order.setStatus(1);
        order.setId(snowflake.nextId());
        orderRepository.save(order);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping(value = "/{userId}/page/{pageNum}")
    public ResponseEntity<Page<Order>> pageOrder(@PathVariable("userId") long userId, @PathVariable("pageNum") int pageNum){
        Pageable pageable = PageRequest.of(pageNum,3);
        Order order = new Order();
        order.setUserId(userId);
        Page<Order> pageData = orderRepository.findAll(Example.of(order), pageable);
        return ResponseEntity.ok(pageData);
    }
}
